package cp4.resp;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

// 实现自动率先你
public class RefreshServlet extends HttpServlet {
    // 刷新次数
    private int refreshCount = 0;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 设置响应中文乱码
        resp.setContentType("text/html;charset=utf-8");
        resp.setCharacterEncoding("utf-8"); // 最关键的
        // 设置刷新的头
        PrintWriter out = resp.getWriter();
        out.println("refresh count is:" + refreshCount);
        out.println("<h1>将在<span id=\"ttt\">5</span>秒后刷新</h1>\n" +
                "<script>\n" +
                "const t = document.querySelector('#ttt');\n" +
                "let time = 5;\n" +
                "const timer = setInterval(()=>{\n" +
                "\tif(time -- == 0){\n" +
                "\t\tlocation.reload();//刷新\n" +
                "\t\tclearInterval(timer);\n" +
                "\t\treturn;\n" +
                "\t}\n" +
                "\tt.innerHTML = time;\n" +
                "},1000);\n" +
                "</script>");
        refreshCount++;
    }
}
